import hashlib
import os
import shutil
import requests
from utils.common_util import CommonUtil

def get_sign():
    se = 'fcc5d76fc3394cd4e088ab349521ba3c'
    data = {
        'app_id': "990",
        'items': "head_estimation"
    }

    secret = se
    stringA = '&'.join(["{0}={1}".format(k, data.get(k)) for k in sorted(data)])
    timestamp = str(CommonUtil.get_timestamp())
    stringA = "{}{}{}".format(secret, stringA, timestamp)
    md5 = hashlib.md5()
    md5.update(stringA.encode("utf8"))
    a, b = md5.hexdigest(), timestamp
    return a, b

if __name__ == '__main__':
    a, b = get_sign()
    print(a, b)
    url = 'https://detect.idimage.cn/api/external/main'
    data_dir = r"C:\Users\admin\Desktop\head\judge"
    data_dir_2 = r"C:\Users\admin\Desktop\head\judge_new"
    path_list = []

    for i in os.listdir(data_dir):
        path_list.append(os.path.join(data_dir, i))

    data_dict = {
        "app_id": "990",
        "items": "head_estimation",
        "timestamp": b,
        "sign": a
    }

    for path in path_list:
        filename = os.path.basename(path)
        if not filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            print(f"Warning: {filename} is not a valid image format.")
            continue

        try:
            with open(path, "rb") as file:
                # 包装文件对象为二元组形式
                files = {'det_main': (filename, file, 'image/jpg')}
                res = requests.post(url, data=data_dict, files=files)
                data = res.json()

                if 'result' in data and 'head_estimation' in data['result']:
                    result = data['result']['head_estimation']['result']
                    yaw_value = result['yaw']['value']
                    pitch_value = result['pitch']['value']
                    # 创建 TXT 文件
                    txt_filename = f"{os.path.splitext(filename)[0]}.txt"
                    txt_path = os.path.join(data_dir_2, txt_filename)
                    with open(txt_path, "w") as txt_file:
                        txt_file.write(f"Filename: {filename}\n")
                        txt_file.write(f"Yaw Value: {yaw_value}\n")
                        txt_file.write(f"Pitch Value: {pitch_value}\n")
                    print(f"Created TXT file: {txt_filename}")

                    if abs(yaw_value) >= 8:
                        # 移动图片到 data_dir_2
                        new_path = os.path.join(data_dir_2, filename)
                        shutil.move(path, new_path)
                        print(f"Moved {filename} to {data_dir_2}")

                    else:
                        print(f"Yaw value {yaw_value} is within the threshold.")

                else:
                    print(f"Missing 'result' or 'head_estimation' in response: {data}")

        except PermissionError as e:
            print(f"PermissionError: {e}")
            continue

        except Exception as e:
            print(f"Error processing {path}: {e}")
            continue